﻿using System;
using System.Collections.Generic;
using System.Reflection;
using System.Text;

namespace Yamibuy.Framework.Core.Tools
{
	public static class ClassMapper
	{
		public static T ToType<T>(this object boj) where T : new()
		{
			if (boj == null)
			{
				return default(T);
			}
			T entity = new T();
			PropertyInfo[] pps = GetPropertyInfos(boj.GetType());
			Type target = entity.GetType();
			foreach (var pp in pps)
			{
				PropertyInfo targetPP = target.GetProperty(pp.Name);
				object value = pp.GetValue(boj, null);

				if (targetPP != null && value != null)
				{
					targetPP.SetValue(entity, value, null);
				}
			}
			return entity;
		}

		public static List<T> ToTypeList<S, T>(this IList<S> list) where T : new()
		{
			List<T> result = new List<T>();
			foreach (var item in list)
			{
				if (item == null)
				{
					continue;
				}
				T entity = new T();
				PropertyInfo[] pps = GetPropertyInfos(item.GetType());
				Type target = entity.GetType();
				foreach (var pp in pps)
				{
					PropertyInfo targetPP = target.GetProperty(pp.Name);
					object value = pp.GetValue(item, null);

					if (targetPP != null && value != null)
					{
						targetPP.SetValue(entity, value, null);
					}
				}
				result.Add(entity);
			}
			return result;
		}

		public static PropertyInfo[] GetPropertyInfos(Type type)
		{
			return type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
		}

		//public static void AutoMapping<S, T>(S s, T t)
		//{
		//    // get source PropertyInfos
		//    PropertyInfo[] pps = GetPropertyInfos(s.GetType());
		//    // get target type
		//    Type target = t.GetType();

		//    foreach (var pp in pps)
		//    {
		//        PropertyInfo targetPP = target.GetProperty(pp.Name);
		//        object value = pp.GetValue(s, null);

		//        if (targetPP != null && value != null)
		//        {
		//            targetPP.SetValue(t, value, null);
		//        }
		//    }
		//}
	}
}
